package com.canbot.u05.activity.firstguide

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.BaseActivityNoTitle
import com.canbot.u05.activity.admin.TokenProccessor
import com.canbot.u05.activity.editmodule.AppInfoSelctAdapter
import com.canbot.u05.activity.editmodule.AppInfoUnSelctAdapter
import com.canbot.u05.activity.editmodule.HorizontalLinearLayoutManager
import com.canbot.u05.activity.editmodule.SpacesItemDecoration
import com.canbot.u05.activity.loge
import com.canbot.u05.activity.showToast
import com.canbot.u05.bean.AdminInfoBean
import com.canbot.u05.bean.AppInfo
import com.canbot.u05.bean.JsonResponse
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.socket.MsgSendUtils
import com.canbot.u05.socket.MsgType
import com.canbot.u05.utils.OkHttpUtils
import com.canbot.u05.utils.PathConst
import com.canbot.u05.utils.SPUtils
import com.canbot.u05.widget.LoadingDialogUtils
import kotlinx.android.synthetic.main.activity_edit_secne_module.*
import java.util.*

/**
 * desc: 场景应用选择界面
 * author: xxl
 * date: 2019/6/19
 */
class SceneModuleActivity : BaseActivityNoTitle() {
    private lateinit var appInfoSelctAdapter: AppInfoSelctAdapter
    private lateinit var appInfoUnSelctAdapter: AppInfoUnSelctAdapter
    private var selectModules: ArrayList<AppInfo> = ArrayList()
    private var unSelectModules: ArrayList<AppInfo> = ArrayList()
    private var scene: String = ""
    private var dialogLoading: Dialog? = null
    private var password: String? = null


    private val helper = ItemTouchHelper(object : ItemTouchHelper.Callback() {
        //线性布局和网格布局都可以使用
        override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
            var dragFrlg = 0
            if (recyclerView.layoutManager is GridLayoutManager) {
                dragFrlg = ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
            } else if (recyclerView.layoutManager is LinearLayoutManager) {
                dragFrlg = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
            }
            return ItemTouchHelper.Callback.makeMovementFlags(dragFrlg, 0)
        }

        override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {

            //得到当拖拽的viewHolder的Position
            val fromPosition = viewHolder.adapterPosition
            //拿到当前拖拽到的item的viewHolder
            val toPosition = target.adapterPosition
            if (fromPosition < toPosition) {
                for (i in fromPosition until toPosition) {
                    Collections.swap(selectModules, i, i + 1)
                }
            } else {
                for (i in fromPosition downTo toPosition + 1) {
                    Collections.swap(selectModules, i, i - 1)
                }
            }

            appInfoSelctAdapter.notifyItemMoved(fromPosition, toPosition)
            return true
        }

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}

        override fun isLongPressDragEnabled(): Boolean {
            return true
        }

        /**
         * 长按选中Item的时候开始调用
         * 长按高亮
         */
        override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {

                viewHolder!!.itemView.setBackgroundResource(R.drawable.shape_item_moudle_bg_drag)
            }
            super.onSelectedChanged(viewHolder, actionState)
        }

        /**
         * 手指松开的时候还原高亮
         */
        override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
            super.clearView(recyclerView, viewHolder)
            viewHolder.itemView.setBackgroundResource(R.drawable.shape_item_moudle_bg_nor)
            appInfoSelctAdapter.notifyDataSetChanged()  //完成拖动后刷新适配器，这样拖动后删除就不会错乱
        }
    })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_secne_module)
        scene = intent.getStringExtra("scene")
        password = intent.getStringExtra("password")

        selectModules = ArrayList()
        unSelectModules = ArrayList()

        if (scene != getString(R.string.scene_name_zdy)) {
            tv_common_modules.text = scene + getString(R.string.common_modules)
        }

        val layoutManager = HorizontalLinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL

        rv_select.layoutManager = layoutManager
        rv_select.addItemDecoration(SpacesItemDecoration(resources.getDimension(R.dimen.px21).toInt()))
        appInfoSelctAdapter = AppInfoSelctAdapter(this, selectModules, R.layout.item_module_selected)
        rv_select.adapter = appInfoSelctAdapter
        helper.attachToRecyclerView(rv_select)

        val layoutManager2 = HorizontalLinearLayoutManager(this)
        layoutManager2.orientation = LinearLayoutManager.HORIZONTAL
        rv_unselect.layoutManager = layoutManager2
        rv_unselect.addItemDecoration(SpacesItemDecoration(resources.getDimension(R.dimen.px21).toInt()))
        appInfoUnSelctAdapter = AppInfoUnSelctAdapter(this, unSelectModules, R.layout.item_module_unselected)
        rv_unselect.adapter = appInfoUnSelctAdapter

        appInfoUnSelctAdapter.setSelectAdapter(appInfoSelctAdapter)
        appInfoSelctAdapter.setUnselectAdapter(appInfoUnSelctAdapter)

        requestAppInfo()

        tv_next_step.setOnClickListener {
            val allAppInfos = appInfoSelctAdapter.allAppInfos

            loge("allAppInfos:" + allAppInfos.size)

            if (allAppInfos.isEmpty()) {
                Toast.makeText(this@SceneModuleActivity, getString(R.string.scene_data_failed), Toast.LENGTH_SHORT).show()
            }else{
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this@SceneModuleActivity, resources.getString(R.string.data_upload))
                //保存信息（步骤：1，保存场景应用配置信息；2，保存管理员信息（密码）；3，管理员信息保存成功后保存token信息）
                saveSceneModules()
            }

        }
    }

    override fun onResume() {
        super.onResume()
        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.ADMIN_AUDIO_PATH + "gntj_szscyd_u05_001.mp3")
    }

    /**
     * 保存管理员信息
     */
    private fun saveAdminInfo() {
        val params = HashMap<String, String>()
        val bean = AdminInfoBean()
        bean.id = 1
        bean.password = password
        val jsonString = JSON.toJSONString(bean)

        params["adminType"] = "addAdmin"
        params["addAdmin"] = jsonString

        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "admin", params, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {

                val jsonResponse = JSON.parseObject(result, JsonResponse::class.java)
                runOnUiThread {
                    if (jsonResponse.rc == -1) { //设置管理员信息失败
                        loge("管理员信息保存失败")
                        showToast("数据保存失败")
                        cancelDialog()

                    } else if (jsonResponse.rc == 0) { //设置管理员信息成功
                        loge("管理员信息保存成功")
                        saveToken()//保存token信息
                    }
                }

            }

            override fun onFailure() {
                loge("保存管理员信息失败,服务器异常,请重试!")
                showToast("服务器异常,请重试!")
                runOnUiThread { cancelDialog() }
            }
        })
    }

    /**
     * 保存token信息
     */
    private fun saveToken() {
        var token: String = SPUtils.getString(this, "token", "")
        if (TextUtils.isEmpty(token)) {
            token = TokenProccessor.getInstance().makeToken()
        }

        val hasMap = HashMap<String, Any>()
        hasMap["adminType"] = "addToken"
        hasMap["addToken"] = token

        val finalToken = token
        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "admin", hasMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)
                if (strMsgBean.rc == 0) {
                    showToast("数据保存成功")
                    loge("saveToken:$finalToken")
                    SPUtils.saveString(this@SceneModuleActivity, "token", finalToken) //token上传服务器成功后保存本地
                } else {
                    showToast("token数据保存失败")
                }

                runOnUiThread {
                    cancelDialog()
                    startActivity(Intent(this@SceneModuleActivity, MapInstructionActivity::class.java))
                }
            }

            override fun onFailure() {
                loge("保存token信息失败,服务器异常,请重试!")
                showToast("服务器异常,请重试!")
                runOnUiThread { cancelDialog() }
            }
        })

    }

    /**
     * 保存场景应用信息
     */
    private fun saveSceneModules() {
        val allAppInfos = appInfoSelctAdapter.allAppInfos
        val jsonStr = JSON.toJSONString(allAppInfos)
        val hasMap = HashMap<String, Any>()
        hasMap["edit_list"] = jsonStr
        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "appInfo", hasMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)
                if (strMsgBean.rc == 0) {
                    loge("场景数据保存成功")
                    saveAdminInfo()    //保存管理员信息
                } else {
                    showToast("场景数据保存失败")
                    runOnUiThread { cancelDialog() }
                }
            }

            override fun onFailure() {
                loge("场景数据保存失败,服务器异常,请重试!")
                showToast("服务器异常,请重试!")
                runOnUiThread { cancelDialog() }
            }
        })
    }

    /**
     * 请求场景应用数据
     */
    private fun requestAppInfo() {
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this@SceneModuleActivity, resources.getString(R.string.request))
        val hasMap = HashMap<String, Any>()
        hasMap["get_data"] = "get_data"
        if (scene != getString(R.string.scene_name_zdy)) {
            hasMap["scene"] = scene
            loge("scene:$scene")
        }


        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "appInfo", hasMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                loge("success ： $result")

                val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)

                if (strMsgBean.rc == 0) {

                    loge("success ： 获取数据成功")
                    val str = strMsgBean.result.toString()
                    val appInfos = JSON.parseArray(str, AppInfo::class.java)
                    splitAppInfos(appInfos)

                    runOnUiThread { cancelDialog() }


                } else {
                    showToast("获取数据失败")
                    runOnUiThread { cancelDialog() }
                }


            }

            override fun onFailure() {
                showToast(getString(R.string.service_error_hint))
                loge("getData onFailure")
                runOnUiThread { cancelDialog() }
            }
        })
    }

    /**
     * 取消加载的Dialog
     */
    private fun cancelDialog() {
        if (dialogLoading!= null && dialogLoading!!.isShowing) {
            dialogLoading?.cancel()
        }
    }

    /**
     * 分离数据
     */
    private fun splitAppInfos(appInfos: List<AppInfo>) {
        selectModules.clear()
        unSelectModules.clear()

        for (appInfo in appInfos) {
            if (appInfo.isMainFunction) {
                selectModules.add(appInfo)
            } else {
                unSelectModules.add(appInfo)
            }
        }

        if (selectModules.size > 1) {
            Collections.sort(selectModules) { o1, o2 -> o1.position - o2.position }
        }

        runOnUiThread {
            appInfoSelctAdapter.setDatas(selectModules)
            appInfoUnSelctAdapter.setDatas(unSelectModules)
        }


    }

    override fun onPause() {
        super.onPause()
        cancelDialog()
    }

    fun back(view: View) = finish()

}
